package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class RequestProcessor extends Thread {

    private Socket socket;
    private List<Context> contexts;


    public RequestProcessor(Socket socket, List<Context> contexts) {
        this.socket = socket;
        this.contexts = contexts;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //获取请求的应用名：demo1 (http://localhost:8080/demo1/lagou)
            String requestContextName = request.getUrl().split("/")[1];
            //获取请求的url:/lagou (http://localhost:8080/demo1/lagou)
            String url = request.getUrl().replace("/" + requestContextName, "");

            //根据request.url匹配webapps中的应用及Servlet
            Optional<Context> optional = contexts.stream().filter(context -> requestContextName.equals(context.getName())).findFirst();

            if(optional.isEmpty() || optional.get().getServletMapping().get(url) == null){
                // 静态资源处理
                response.outputHtmlWithAbsolutePath(optional.get().getHtmlPath()+url);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = optional.get().getServletMapping().get(url);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
